package com.zhongxiangspace.controller.member;

import com.zhongxiangspace.entity.UserInfo;
import com.zhongxiangspace.result.NormalResult;
import com.zhongxiangspace.result.Result;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MemberLoginController {


    @ResponseBody
    @PostMapping("memberLoin.do")
    public Result  memberLoin(HttpServletRequest request,UserInfo userInfo) throws Exception{

        NormalResult result =  null;
        String captcha= (String) request.getSession(true).getAttribute("captcha");
        System.out.println(captcha+"---------->"+userInfo.getVerify());
           if (captcha==null || captcha.isEmpty()){
            result=new NormalResult("验证码过期！");
            return result;
        }  else   if (StringUtils.isNotEmpty(userInfo.getVerify())&&!StringUtils.equals(captcha.toLowerCase(),userInfo.getVerify().toLowerCase())){
            result=new NormalResult("验证码错误！");
            return result;
        }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword(),userInfo.getVerify());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
      //  session.setTimeout(1800000);
        try {
            subject.login(usernamePasswordToken);
            UserInfo user = (UserInfo) subject.getPrincipal();
            subject.getSession().setAttribute("username", user);
            System.out.println(subject.getSession().getTimeout());
            result=new NormalResult("SUCCESS");
        }catch (Exception e){
            System.out.println(e.getMessage()+"-->"+e.getClass().getName());
            result=new NormalResult("帐号/密码错误！");
        }
        return result;
    }

}
